<template>
  <SearchResults
    v-if="items && items.results.length"
    :title="title"
    :items="items"
    :loading="loading"
    @loadMore="loadMore"
  />
</template>
<script setup>
import { search } from "@/api";
import SearchResults from "@/components/SearchResults.vue";
import { ref, computed } from "vue";
import {
  useRoute,
  useRouter,
  onBeforeRouteLeave,
  onBeforeRouteUpdate,
} from "vue-router";
import { useSearchStore } from "@/store/useSearchStore";

let fromPage = "/";

const loading = ref(false);
const items = ref(null);
const route = useRoute();
const router = useRouter();

const store = useSearchStore();

const query = computed(() => {
  return route.query?.q || "";
});

const title = computed(() => {
  return query.value ? `Results for "${query.value}"` : "";
});

if (query.q) {
  search(query.q, 1).then((response) => {
    items.value = response;
  });
} else {
  router.redirect("/");
}

store.openSearch();
store.setFromPage(fromPage);

const getResults = () => {
  if (!query.value.length) {
    items.value = null;
    return;
  }
  search(query.value).then((res) => {
    if (!res.total_results) {
      items.value = null;
      return;
    }
    items.value = res;
  });
};

const loadMore = () => {
  loading.value = true;

  search(query.value, items.value.page + 1)
    .then((res) => {
      items.value.results = items.value.results.concat(res.results);
      items.value.page = res.page;
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
};

onBeforeRouteUpdate(async (to, from) => {
  fromPage = from.path;
  getResults();
});

onBeforeRouteLeave((to, from, next) => {
  const search = document.getElementById("search");
  next();
  if (search && search.value.length) {
    store.closeSearch();
  }
});
</script>
